﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using VAdvantage.Model;
using VAdvantage.Utility;
using System.Data;
using VAdvantage.DataBase;
using System.ComponentModel;
using VAdvantage.Classes;

namespace VAdvantage.Apps
{
    public partial class AddKPI : CFrame
    {

        public AddKPI(int _CurrentKPIPane_ID, int _kpicenterid)
        {
            Utility.Envs.RegisterWindowForm(this);
            this.Top = 120;
            this.Left = 330;
            CurrentKPIPane_ID = _CurrentKPIPane_ID;
            KPICenter_ID = _kpicenterid;
            InitializeComponent();
            LoadKPIData();
        }

        List<KeyNamePair> listKPI = new List<KeyNamePair>();
        List<KeyNamePair> listKPIPane = new List<KeyNamePair>();
        List<KeyNamePair> listAllKPI = new List<KeyNamePair>();
        List<KeyNamePair> listColors = new List<KeyNamePair>();
        int CurrentKPIPane_ID = 0;
        int KPICenter_ID = 0;
        int SelectedKPI = 0;

        void LoadKPIData()
        {
            SetBusy(true, "Loading...");
            BackgroundWorker bgw = new BackgroundWorker();

            bgw.DoWork += (o, e) =>
                {
                    string sql = "Select RC_KPI.RC_KPI_ID, RC_KPI.Name from RC_KPI RC_KPI WHERE IsActive = 'Y'  AND ( " + Envs.GetCtx().GetAD_Role_ID() + " IN (select ad_role_id from RC_KPIAccess where RC_KPI.RC_KPI_ID = RC_KPI_ID ) OR " + Envs.GetCtx().GetAD_User_ID() + " IN ( SELECT AD_User_ID FROM RC_KPIAccess WHERE RC_KPI.RC_KPI_ID = RC_KPI_ID )) ";
                    string s = MRole.GetDefault().AddAccessSQL(sql, "RC_KPI", true, false);
                    IDataReader dr = DB.ExecuteReader(s);

                    if (dr != null)
                    {
                        while (dr.Read())
                        {
                            KeyNamePair key = new KeyNamePair(int.Parse(dr[0].ToString()), dr[1].ToString());
                            listKPI.Add(key);
                        }
                        dr.Close();
                    }


                    sql = "Select RC_KPIPane_ID, Name from RC_KPIPane where IsActive = 'Y' Order by seqno";
                    dr = DB.ExecuteReader(sql);
                    while (dr.Read())
                    {
                        KeyNamePair key = new KeyNamePair(int.Parse(dr[0].ToString()), dr[1].ToString());
                        listKPIPane.Add(key);
                    }
                    dr.Close();

                    sql = "Select RC_KPICenter_ID, Name from RC_KPICenter where IsActive = 'Y' AND RC_KPIPane_ID = " + CurrentKPIPane_ID + " Order by seqno ";
                    dr = DB.ExecuteReader(sql);
                    while (dr.Read())
                    {
                        KeyNamePair key = new KeyNamePair(int.Parse(dr[0].ToString()), dr[1].ToString());
                        listAllKPI.Add(key);
                    }
                    dr.Close();

                    //sql = "Select AD_PrintColor_ID, Name from AD_PrintColor WHERE IsActive = 'Y'";
                    //dr = DB.ExecuteReader(sql);
                    //while (dr.Read())
                    //{
                    //    KeyNamePair key = new KeyNamePair(int.Parse(dr[0].ToString()), dr[1].ToString());
                    //    listColors.Add(key);
                    //}
                    //dr.Close();
                };


            bgw.RunWorkerCompleted += (o, e) =>
                {
                    cmbKPIPanel.IsEnabled = false;
                    for (int a = 0; a <= listKPI.Count - 1; a++)
                        cmbKPI.Items.Add(listKPI[a]);

                    for (int a = 0; a <= listKPIPane.Count - 1; a++)
                    {
                        cmbKPIPanel.Items.Add(listKPIPane[a]);
                        if ((listKPIPane[a] as KeyNamePair).GetKey() == CurrentKPIPane_ID)
                            cmbKPIPanel.SelectedIndex = a;
                    }


                    //for (int a = 0; a <= listColors.Count - 1; a++)
                    //    cmbFontColor.Items.Add(listColors[a]);

                    for (int a = 0; a <= listAllKPI.Count - 1; a++)
                    {
                        lstAddedKPI.Items.Add(listAllKPI[a]);
                        if ((listAllKPI[a] as KeyNamePair).GetKey() == KPICenter_ID)
                            lstAddedKPI.SelectedIndex = a;
                    }
                    SetBusy(false);
                };

            bgw.RunWorkerAsync();
        }


        void SetBusy(bool b)
        {
            SetBusy(false, "");
        }

        void SetBusy(bool b, String t)
        {
            if (b)
            {
                busyWindow.Visibility = System.Windows.Visibility.Visible;
                txtBusy.Visibility = System.Windows.Visibility.Visible;
            }
            else
            {
                busyWindow.Visibility = System.Windows.Visibility.Collapsed;
            }
            txtBusy.Text = t;

        }

        private string GetKPIQuery(string dynSql, string tableName)
        {
            MRole role = MRole.Get(Envs.GetCtx(), Envs.GetCtx().GetAD_Role_ID());
            return role.AddAccessSQL(dynSql, tableName, false, false);
        }

        private void btnCancel_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void btnOK_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (cmbKPI.SelectedIndex < 0)
                {
                    ShowMessage.Error("SelectKPI", false);
                    return;
                }
                else if (cmbKPIPanel.SelectedIndex < 0)
                {
                    ShowMessage.Error("SelectKPIPanel", false);
                    return;
                }
                else if (string.IsNullOrEmpty(txtName.Text))
                {
                    ShowMessage.Error("EnterName", false);
                    return;
                }

                SetBusy(true, "Saving");
                string name = txtName.Text;
                int kpi_id = (cmbKPI.SelectedItem as KeyNamePair).GetKey();
                int kpipane_id = (cmbKPIPanel.SelectedItem as KeyNamePair).GetKey();
                int seqno = int.Parse(txtSeq.Text);

                //int fontcolor_id = 0;
                //if(cmbFontColor.SelectedIndex >= 0)
                //    fontcolor_id = (cmbFontColor.SelectedItem as KeyNamePair).GetKey();
                bool b = false;

                KeyNamePair newKPI = null;
                BackgroundWorker bgw = new BackgroundWorker();
                bgw.DoWork += (o, ev) =>
                    {
                        X_RC_KPICenter rc = new X_RC_KPICenter(Envs.GetCtx(), SelectedKPI, null);
                        rc.SetName(name);
                        rc.SetRC_KPI_ID(kpi_id);
                        rc.SetRC_KPIPane_ID(kpipane_id);
                        //rc.SetFont_Color_ID(fontcolor_id);
                        rc.SetSeqNo(seqno);
                       
                        b = rc.Save();

                        if (b)
                        {
                            newKPI = new KeyNamePair(rc.Get_ID(), name);
                        }
                    };

                bgw.RunWorkerCompleted += (o, ev) =>
                    {
                        if (b)
                        {
                            ShowMessage.Info("RecordSaved", false, "", "");

                            if(SelectedKPI <= 0)
                                lstAddedKPI.Items.Add(newKPI);

                            SelectedKPI = 0;
                            cmbKPI.SelectedIndex = -1;
                            txtName.Text = "";
                            txtSeq.Text = "0";
                            lstAddedKPI.SelectedIndex = -1;
                        }
                        else
                            ShowMessage.Info("RecordNotSaved", false, "", "");

                        SetBusy(false);
                    };

                bgw.RunWorkerAsync();
            }
            catch
            {
                ShowMessage.Info("InvalidData", false, "", "");
            }
        }


        int selectedValue = 0;
        private void lstAddedKPI_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (lstAddedKPI.SelectedIndex < 0)
                return;

            stillLoading = true;
            cmbKPI.IsEnabled = false;
            SetBusy(true, "Loading");
            KeyNamePair key = (lstAddedKPI.SelectedItem as KeyNamePair);
            SelectedKPI = key.GetKey();

            IDataReader dr = null;
            BackgroundWorker bgw = new BackgroundWorker();
            bgw.DoWork += (o, ev) =>
            {
                string sql = "Select Name, Font_Color_ID, RC_Kpi_ID, SeqNo from Rc_KPICenter where IsActive = 'Y' And RC_KpiCenter_ID = " + SelectedKPI;
                dr = DB.ExecuteReader(sql);
            };

            bgw.RunWorkerCompleted += (o, ev) =>
            {
                while (dr.Read())
                {
                    txtName.Text = key.GetName();
                    txtSeq.Text = dr["SeqNo"].ToString();
                    //for (int c = 0; c <= cmbFontColor.Items.Count - 1; c++)
                    //{
                    //    KeyNamePair color = (cmbFontColor.Items[c] as KeyNamePair);
                    //    if (color.GetKey() == int.Parse(dr["Font_Color_ID"].ToString()))
                    //        cmbFontColor.SelectedIndex = c;
                    //}

                    for (int c = 0; c <= cmbKPI.Items.Count - 1; c++)
                    {
                        KeyNamePair kpi = (cmbKPI.Items[c] as KeyNamePair);
                        if (kpi.GetKey() == int.Parse(dr["RC_Kpi_ID"].ToString()))
                            cmbKPI.SelectedIndex = c;
                    }
                }
                dr.Close();
                SetBusy(false);
                stillLoading = false;
            };

            bgw.RunWorkerAsync();
        }

        private void btnRemoveKPI_Click(object sender, RoutedEventArgs e)
        {
            if (lstAddedKPI.SelectedIndex < 0)
                return;
            SetBusy(true, "Deleting");
            bool b = false;
            BackgroundWorker bgw = new BackgroundWorker();
            bgw.DoWork += (o, ev) =>
            {
                X_RC_KPICenter rc = new X_RC_KPICenter(Envs.GetCtx(), SelectedKPI, null);
                b = rc.Delete(true);
            };

            bgw.RunWorkerCompleted += (o, ev) =>
            {
                if (b)
                {
                    if(lstAddedKPI.SelectedIndex >= 0)
                        lstAddedKPI.Items.RemoveAt(lstAddedKPI.SelectedIndex);

                    ShowMessage.Info("RecordDeleted", false, "", "");

                    SelectedKPI = 0;
                    cmbKPI.SelectedIndex = -1;
                    txtName.Text = "";
                    txtSeq.Text = "0";
                    lstAddedKPI.SelectedIndex = -1;
                }
                else
                    ShowMessage.Info("DeleteError", false, "", "");

                SetBusy(false);
            };
            bgw.RunWorkerAsync();
        }

        private void btnAddNew_Click(object sender, RoutedEventArgs e)
        {
            SelectedKPI = 0;
            cmbKPI.SelectedIndex = -1;
            txtName.Text = "";
            txtSeq.Text = "0";
            lstAddedKPI.SelectedIndex = -1;
            cmbKPI.IsEnabled = true;
        }

        private void btnUp_Click(object sender, RoutedEventArgs e)
        {

        }

        bool stillLoading = false;
        private void cmbKPIPanel_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (stillLoading)
                return;

            KeyNamePair key = cmbKPI.SelectedItem as KeyNamePair;
            if(key == null)
                return;

            //lstAddedKPI.SelectedIndex = -1;

            string name = "";
            int kpiid = key.GetKey();
            BackgroundWorker bgw = new BackgroundWorker();
            bgw.DoWork += (o, ev) =>
                {
                    string sql = "Select SearchKey from RC_KPI WHERE RC_KPI_ID = " + kpiid;
                    IDataReader dr = DB.ExecuteReader(sql);
                    while (dr.Read())
                    {
                        name = dr[0].ToString();
                    }
                    dr.Close();
                };

            bgw.RunWorkerCompleted += (o, ev) =>
                {
                    txtName.Text = name;
                };

            bgw.RunWorkerAsync();
        }
    }
}
